//
//  CFSHttpRequest.swift
//  eval
//
//  Created by hengchengfei on 15/10/14.
//  Copyright © 2015年 chengfeisoft. All rights reserved.
//

import UIKit
import IOSCommon
import ObjectMapper

public func cfsRequest<T:Mappable>(
    method:CFSHTTPMethod,
    _ URLString:String,
    parameters:[String: AnyObject]? = nil,
    encoding:CFSHTTPParameterEncoding? = CFSHTTPParameterEncoding.URL,
    headers: [String: String]? = nil,
    success:((statusCode:Int?,data:NSDictionary?,model:T?) -> Void)?,
    failure:((statusCode:Int?,message:String) -> Void)?  = nil){
        
        let URL = SERVER + URLString
        
        //其他信息
        var _params:[String: AnyObject]? = parameters
        if parameters == nil {
            _params = [String: AnyObject]()
        }
        
        //打印参数
        if let p = parameters {
            var s = "?"
            for (key,value) in p {
                s = s + key + "=" + "\(value)" + "&"
            }
            let p1 = s.substringToIndex(s.endIndex.advancedBy(-1))
            log.info("\(URL)\(p1)")
        }else{
            log.info("\(URL)")
        }
        
        request(method, URL, parameters: _params, encoding: encoding, headers: headers, success: { (statusCode, data, model:T?) -> Void in
            //log.info("\(data)")
            if success != nil {
                success!(statusCode: statusCode,data: data,model: model)
            }
            }) { (statusCode, message) -> Void in
                log.error("statusCode = \(statusCode),message = \(message)")
                if failure != nil {
                    failure!(statusCode: statusCode,message: message)
                }
        }
        
}